/*
This file is part of IRCaBot.
IRCaBot is IRC logger with features.
Source code: https://notabug.org/acetone/ircabot.
Copyright (C) acetone, 2023.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "logger.h"
#include "config.h"

#include <QMutex>
#include <QRegularExpression>
#include <QFile>
#include <QDebug>
#include <QDateTime>

#include <iostream>

namespace logger {

Level level = Level::Info;

QString levelString(Level level)
{
    switch(level)
    {
    case Level::Debug:
        return "debug";
    case Level::Error:
        return "error";
    case Level::Info:
        return "info";
    case Level::Warning:
        return "warning";
    case Level::Off:
        return "off";
    default:
        return "unknown";
    }
}

void customMessageOutput(QtMsgType type, const QMessageLogContext&, const QString &msg)
{
    if (level == Level::Off) return;

    static QMutex mtx;
    QMutexLocker lock (&mtx);

    QString logLine;
    if (type == QtDebugMsg)
    {
        if (level == Level::Debug)
        {
            logLine = "[Dbug]: " + msg;
            std::cout << logLine.toStdString() << std::endl;
        }
    }

    else if (type == QtInfoMsg)
    {
        if (level >= Level::Info)
        {
            logLine = "[Info]: " + msg;
            std::cout << logLine.toStdString() << std::endl;
        }
    }

    else if (type == QtWarningMsg)
    {
        if (level >= Level::Warning)
        {
            logLine = "[Warn]: " + msg;
            std::cerr << logLine.toStdString() << std::endl;
        }
    }

    else if (type == QtCriticalMsg)
    {
        if (level >= Level::Error)
        {
            logLine = "[Erro]: " + msg;
            std::cerr << logLine.toStdString() << std::endl;
        }
    }

    else if (type == QtFatalMsg)
    {
        if (level >= Level::Error)
        {
            logLine = "[Fatl]: " + msg;
            std::cerr << logLine.toStdString() << std::endl;
        }
    }

    if (not logLine.isEmpty() and not Config::logFilePath().isEmpty())
    {
        QFile file(Config::logFilePath());
        if (not file.open(QIODevice::WriteOnly | QIODevice::Append))
        {
            qCritical() << "Can't write log file" << Config::logFilePath();
            return;
        }
        const QString& dateFormat = Config::logFileDateFormat();
        file.write( QDateTime::currentDateTime().toString(dateFormat).toUtf8() +
                    (dateFormat.isEmpty() ? "" : " ") +
                    logLine.toUtf8() + "\n" );
        file.close();
    }
}

Level levelEnum(const QString &str)
{
    static const QRegularExpression rgx_Debug   ("^debug$", QRegularExpression::CaseInsensitiveOption);
    static const QRegularExpression rgx_Warning ("^warn(ing)?$", QRegularExpression::CaseInsensitiveOption);
    static const QRegularExpression rgx_Error   ("^err(or)?$", QRegularExpression::CaseInsensitiveOption);
    static const QRegularExpression rgx_Off     ("^off$", QRegularExpression::CaseInsensitiveOption);

    // If unknown, then Info
    return str.contains(rgx_Debug) ?   Level::Debug :
           str.contains(rgx_Off) ?     Level::Off :
           str.contains(rgx_Warning) ? Level::Warning :
           str.contains(rgx_Error) ?   Level::Error :
                                       Level::Info;
}

} // namespace
